#引入模块
import json
import os
import mc

#变量声明
configf = 'plugins/home/config.json'
homelistf = 'plugins/home/homelist.json'
path = 'plugins/home'
Home_Form_Id = 114514

#读取Config文件函数
def readconfig():
    try:
        with open(configf,'r',encoding='UTF-8') as f:
            d = f.read()
            global config
            config = json.loads(d)
            print('[INFO] Home已经重新读取完成config.json')
    except:
        print('[INFO] Home读取出错使用内置Config.Json')
        config = {"maxhome": 6,"lastpos": False}

#读取homelist函数
def readhomelist():
    try:
        with open(homelistf,'r',encoding='UTF-8') as f:
            d = f.read()
            global homelist
            homelist = json.loads(d)
            print('[INFO] Home已经重新读取完成homelist.json')
    except:
        print('[INFO] Home读取出错使用HomeList.Json')
        homelist = {}

#读取Config文件函数
def read_config():
    try:
        with open(configf,'r',encoding='UTF-8') as f:
            d = f.read()
            global config
            config = json.loads(d)
    except:
        config = {"maxhome": 6,"lastpos": False}

#读取homelist函数
def read_homelist():
    try:
        with open(homelistf,'r',encoding='UTF-8') as f:
            d = f.read()
            global homelist
            homelist = json.loads(d)
    except:
        homelist = {}

#写入文件操作
def Write_File(typea):
    with open(configf,'w') as f:
        f.write(json.dumps(config,sort_keys=True, indent=4, separators=(',', ': ')))
    with open(homelistf,'w') as f:
        f.write(json.dumps(homelist,sort_keys=True, indent=4, separators=(',', ': ')))
    read_config()
    read_homelist()

#文件夹函数
def createFolder(Folderpath):
    try:
        fd = os.path.exists(Folderpath)
        if not fd:
            os.makedirs(Folderpath)
    except:
        print('[INFO] '+Folderpath+'创建失败...')



#首次启动创建文件
def firststart():
    if os.path.isfile(configf):
        readconfig()
    else:
        with open(configf,'w') as f:
            f.write(json.dumps({"maxhome": 6,"lastpos": False},sort_keys=True, 
                indent=4, 
                separators=(',', ': ')))
            print('[INFO] config.json已经创建成功')
    if os.path.isfile(homelistf):
        readhomelist()
    else:
        with open(homelistf,'w') as f:
            f.write('{}')
            print('[INFO] homelist.json已经创建成功')
    print('[INFO] Home Powered By HuoHua...')


#启动函数
def load_plugin():
    createFolder(path)
    firststart()
    readconfig()
    readhomelist()
    try:
        mc.setCommandDescription('home','打开home菜单')
        print('[INFO] 注册命令成功！')
    except:
        print('[INFO] 注册命令失败...')
load_plugin()

#输入指令调用函数
def input_cmd(e):
    global Home_Form_Id
    e['playername'] = mc.getPlayerInfo(e['player'])['playername']
    Home_Name_List = []
    if e['cmd'] == '/home':
        for i in homelist[e['playername']]:
            Text_Color = ''
            if homelist[e['playername']][i]['dim'] == '主世界':
                Text_Color = 'a'
            elif homelist[e['playername']][i]['dim'] == '地狱':
                Text_Color = '4'
            else:
                Text_Color = 'e'
            Home_Text = i+"\n§e"+"维度: "+"§"+Text_Color+homelist[e['playername']][i]['dim'] + " §e坐标: " + str(homelist[e['playername']][i]['x']) + "  " + str(homelist[e['playername']][i]['y']) + "  " +str(homelist[e['playername']][i]['z'])
            Home_Name_List.append({"text":Home_Text})
        Home_Name_List.append({"text":'添加HOME'})
        Home_Name_List.append({"text":'删除HOME'})
        Home_Form_Id = mc.sendSimpleForm(e['player'],'家列表','请选择家：',json.dumps(Home_Name_List))
        return False
mc.setListener('输入指令',input_cmd)
Add_Home = 0
Remove_Home = 0
#表单数据操作
def Form_Action(e):
    global Add_Home,Remove_Home
    #尝试强转值
    try:
        e['selected'] = int(e['selected'])
    except:
        pass
    e['playername'] = mc.getPlayerInfo(e['player'])['playername']
    if e['formid'] == Home_Form_Id:
        Home_List = []
        for i in homelist[e['playername']]:
            Home_List.append(i)
        Home_List.append('添加')
        Home_List.append('移除')
            
        if Home_List[e['selected']] == '移除':
            Home_List = []
            for i in homelist[e['playername']]:
                Home_List.append(i)
            Content = {
                "content":[
                    {"default":0,"options":Home_List,"type":"dropdown","text":"选择要删除的HOME"},
                    {"type":"label","text":"点击提交后将删除HOME"}
                    ],
                    "type":"custom_form",
                    "title":"HOME设置"
                    }
            Remove_Home = mc.sendCustomForm(e['player'],json.dumps(Content))
            
        elif Home_List[e['selected']] == '添加':
            Content = {
                "content":[
                    {"placeholder":"在此输入HOME名称","default":"","type":"input","text":""},
                    {"type":"label","text":"点击提交后将脚下坐标设置为该HOME坐标"}
                    ],
                    "type":"custom_form",
                    "title":"HOME设置"
                    }
            Add_Home = mc.sendCustomForm(e['player'],json.dumps(Content))

        else:
            name = Home_List[e['selected']]
            ass = homelist[e['playername']][Home_List[e['selected']]]
            mc.teleport(e['player'],int(ass['x']),int(ass['y']),int(ass['z']),int(ass['dimid']))
            mc.tellraw(e['player'],'§a§l已成功传送至'+name)

    elif e['formid'] == Add_Home:
        Home_Add_List = []
        for i in homelist[e['playername']]:
            Home_Add_List.append(i)
        player = mc.getPlayerInfo(e['player'])
        null = ''
        e['selected'] = eval(e['selected'])
        poslist = []
        for i in player['XYZ']:
            pos = "%.0f" % i
            poslist.append(int(pos))
            dim = ''
        if player['dimensionid'] == 0:
            dim = '主世界'
        elif player['dimensionid'] == 1:
            dim = '地狱'
        elif player['dimensionid'] == 2:
            dim = '末地'
        if len(Home_Add_List) < int(config['maxhome']):
            homelist[e['playername']][e['selected'][0]] = {"dim":dim,"dimid":player['dimensionid'],"x":poslist[0],"y":poslist[1],"z":poslist[2]}
            Write_File('home')
            mc.tellraw(e['player'],'§a§l'+str(e['selected'][0])+"添加成功")
        else:
            mc.tellraw(e['player'],'§a§l设置的家数量超出限制')
        
    elif e['formid'] == Remove_Home:
        player = mc.getPlayerInfo(e['player'])
        Home_Remove_List = []
        for i in homelist[e['playername']]:
            Home_Remove_List.append(i)
        null = ''
        e['selected'] = eval(e['selected'])
        nsm = Home_Remove_List[e['selected'][0]]
        mc.tellraw(e['player'],'§a§l'+nsm+'删除成功！')
        del homelist[player['playername']][nsm]
        Write_File('home')

#表单监听数据
def Form_Select(e):
    if e['selected'] != 'null':
        Form_Action(e)

mc.setListener('选择表单',Form_Select)

def join(e):
    player = mc.getPlayerInfo(e)['playername']
    if (player in homelist.keys()):
        pass
    else:
        homelist[player] = {}
        Write_File('home')
mc.setListener('加入游戏',join)
